import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import router from './router'
import store from '@/store'
import getPageTitle from './utils/get-page-title.js'
// import { Message } from 'element-ui'
// import { getToken } from '@/utils/auth' // get token from cookie
// import getPageTitle from '@/utils/get-page-title'

// NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login', '/404'] // no redirect whitelist

router.beforeEach((to, from, next) => {
  console.log(to)
  // 要去到的页面中的meta.title
  // 1. 如何设置页面标题？ document.title
  // 2. 路由守卫可以写多个
  document.title = getPageTitle(to.meta.title)
  next()
})

router.beforeEach(async (to, from, next) => {
  NProgress.start()
  const token = store.state.user.token
  if (token) {
    if (to.path === '/login') {
      // 有token，还去登录 ---> 直接去主页
      console.log('有token，还去登录 ---> 直接去主页')
      next('/')
      NProgress.done()
    } else {
      // 1.获取个人信息
      if (!store.getters.userId) {
        await store.dispatch('user/getUserProfile')
      }
      next()
    }
  } else {
    // 没有token，只能访问白名单
    if (whiteList.includes(to.path)) {
      next()
    } else {
      console.log('没有token，只能访问白名单')
      next('/login')
      NProgress.done()
    }
    // whiteList.includes(to.path) ? next() : next('/login')
  }
  console.log(token, '路由跳转', from.path, '----->', to.path)
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
